package com.seselin.joke;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import com.seselin.joke.adapter.SimpleTextAdapter;
import com.seselin.joke.http.HttpExecutor;
import com.seselin.joke.http.JokeBean;
import com.seselin.joke.util.AutoLoadListener;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case HttpExecutor.HTTP_TAG:
                    if (msg.obj == null) {
                        break;
                    }
                    JokeBean bean = (JokeBean) msg.obj;
                    if ("".equals(bean.getResult())) {
                        break;
                    }

                    List<JokeBean.ResultBean.DataBean> list = bean.getResult().getData();
                    dataList.addAll(list);
                    adapter.notifyDataSetChanged();
                    break;
            }
            return false;
        }
    });
    private android.widget.ListView listView;
    private List<JokeBean.ResultBean.DataBean> dataList = new ArrayList<>();
    private SimpleTextAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.listView = (ListView) findViewById(R.id.list_view);

        adapter = new SimpleTextAdapter(this);
        adapter.initData(dataList);
        listView.setAdapter(adapter);

        AutoLoadListener autoLoadListener = new AutoLoadListener(callBack);
        listView.setOnScrollListener(autoLoadListener);

        getData();
    }

    AutoLoadListener.AutoLoadCallBack callBack = new AutoLoadListener.AutoLoadCallBack() {

        public void execute() {
            getData();
        }
    };

    private int pager = 1;

    private void getData() {
        HttpExecutor httpExecutor = new HttpExecutor(handler, pager);
        httpExecutor.start();
        pager++;
    }

}
